import time
from urllib.parse import quote_plus
from alipay import AliPay
from django.conf import settings
from alipay.utils import AliPayConfig
from datetime import datetime

class AliPaySDK(AliPay):
    def __init__(self, config=None):
        if config is None:
            self.config = settings.ALIPAY
        else:
            self.config = config

        app_private_key_string = open(self.config["app_private_key_path"]).read()
        alipay_public_key_string = open(self.config["alipay_public_key_path"]).read()

        super().__init__(
            appid=self.config["appid"],
            app_notify_url=self.config["notify_url"],
            app_private_key_string=app_private_key_string,
            alipay_public_key_string=alipay_public_key_string,
            sign_type=self.config["sign_type"],
            debug=self.config["debug"],
            verbose=self.config["verbose"],
            config=AliPayConfig(timeout=self.config["timeout"])
        )

    def page_pay(self, out_trade_no, total_amount, subject, return_url=None):
        if return_url is None:
            return_url = self.config["return_url"]
        order_string = self.client_api(
            "alipay.trade.page.pay",
            biz_content={
                "out_trade_no": out_trade_no,
                "total_amount": float(total_amount),
                "subject": subject,
                "product_code": "FAST_INSTANT_TRADE_PAY",
            },
            return_url=return_url,
            notify_url=self.config["notify_url"]
        )
        return f"{self.config['gateway']}?{order_string}"

    def check_sign(self, data):
        """
        验证返回的支付结果中的签证信息
        @params data: 支付平台返回的支付结果，字典格式
        """
        signature = data.pop("sign")
        success = self.verify(data, signature)
        return success

    def query(self, out_trade_no):
        """
        根据订单号查询订单状态
        @params out_trade_no: 订单号
        """
        return self.server_api(
            "alipay.trade.query",
            biz_content={
                "out_trade_no": out_trade_no
            }
        )

    def refund(self, out_trade_no, refund_amount):
        """
        原路退款
        @params out_trade_no: 退款的订单号
        @params refund_amount: 退款的订单金额
        """
        self.server_api(
            "alipay.trade.refund",
            biz_content={
                "out_trade_no": out_trade_no,
                "refund_amount": refund_amount
            }
        )

    def transfer(self, account, amount):
        """
        转账给个人
        @params account: 收款人的支付宝账号
        @params amount: 转账金额
        """
        return self.server_api(
            "alipay.fund.trans.toaccount.transfer",
            biz_content={
                "out_biz_no": datetime.now().strftime("%Y%m%d%H%M%S"),
                "payee_type": "ALIPAY_LOGONID",
                # ALIPAY_USERID: 支付宝账号对应的支付宝唯一用户号。以2088开头的16位纯数字组成。
                # # ALIPAY_LOGONID: 支付宝登录号，支持邮箱和手机号格式。
                "payee_account": account,  # 账号
                "amount": amount  # 金额
            }
        )

    def query_transfer(self, trans_time):
        """
        查询转账记录
        @params trans_time: 转账时间[datetime对象]
        """
        return self.server_api(
            "alipay.fund.trans.order.query",
            biz_content={
                "out_biz_no": trans_time.strftime("%Y%m%d%H%M%S"),
            }
        )

def get_alipay_client():
    alipay_config = settings.ALIPAY
    with open(alipay_config['app_private_key_path']) as f:
        private_key = f.read()
    with open(alipay_config['alipay_public_key_path']) as f:
        alipay_public_key = f.read()
    return AliPay(
        appid=alipay_config['appid'],
        app_notify_url=alipay_config['notify_url'],
        app_private_key_string=private_key,
        alipay_public_key_string=alipay_public_key,
        sign_type="RSA2",
        debug=True  # 沙箱环境
    )

